/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.gatech.egg.l0cUs.service.impl;

import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.xeustechnologies.jcl.JarClassLoader;
import org.xeustechnologies.jcl.JclObjectFactory;

/**
 *
 * @author Summers
 */
@Component
public class ModuleService implements org.springframework.beans.factory.InitializingBean {

    private static final Log LOG = LogFactory.getLog(ModuleService.class);
    @Autowired
    ApplicationContext context;

    @Override
    public void afterPropertiesSet() throws Exception {
        File f = new File(ModuleService.class.getClassLoader().getResource("/modules").toURI());
        File files[] = (f.listFiles(new FileFilter() {

            @Override
            public boolean accept(File pathname) {
                return pathname.getName().endsWith("jar");
            }
        }));

        ArrayList<String> fileNames = new ArrayList<String>();

        for (File file : files) {
            fileNames.add(file.toString());
        }

        JarClassLoader jcl = new JarClassLoader(fileNames);
        JclObjectFactory factory = JclObjectFactory.getInstance();

        Map<String, byte[]> classMap = jcl.getLoadedResources();

        for (String clazz : classMap.keySet()) {
            if (clazz.endsWith("class")) {
                Class c = jcl.loadClass(clazz.split("\\.class")[0].replace("/", "."));
                if (!Modifier.isAbstract(c.getModifiers()) && !Modifier.isInterface(c.getModifiers()) && c.getConstructors().length > 0) {
                    context.getAutowireCapableBeanFactory().initializeBean(factory.create(jcl, clazz.split("\\.class")[0].replace("/", ".")), null);
                }
            }
        }



    }
}
